
// Extra/pages/HealthPlan/components/Form/index.js
import { showToast } from '../../../../../utils/util';
const dayjs = require('dayjs');

Component({
  properties: {
    formData: {
      default: {},
      type: Object
    },
    show: {
      default: false,
      type: Boolean
    }
  },
  data: {
    currentDate: null,
    minHour: 0,
    maxHour: 23,
    remind_date: null,
    remind_time: null,
    remind_model: 1,
    remind_type: null,
    device_name: null,
    days: [
      { text: '周一', isChecked: false },
      { text: '周二', isChecked: false },
      { text: '周三', isChecked: false },
      { text: '周四', isChecked: false },
      { text: '周五', isChecked: false },
      { text: '周六', isChecked: false },
      { text: '周日', isChecked: false }
    ]
  },

  observers: {
    formData(newVal) {
      if (Object.keys(newVal).length === 0) return;

      this.setData({
        ...Object.fromEntries(
          Object.entries(newVal)
            .filter(([key]) => this.data.hasOwnProperty(key) && key !== 'days')
            .map(([key, value]) => [`${key}`, value])
        ),
        days: this.data.days.map((item) => ({
          ...item,
          isChecked: newVal.days?.includes(item.text)
        }))
      });
    }
  },

  methods: {
    onTimeConfirm(e) {
      this.setData({ remind_time: e.detail, time_show: false });
    },
    onTimeCancel() {
      this.setData({ time_show: false });
    },
    onClose() {
      this.triggerEvent('close');
    },
    onShowTime() {
      this.setData({ time_show: true });
    },
    onChange(e) {
      this.setData({ remind_model: e.detail ? 0 : 1 });
    },
    onChoose(e) {
      this.setData({
        days: this.data.days.map((item, index) =>
          index === e.currentTarget.dataset.index
            ? { ...item, isChecked: !item.isChecked }
            : item
        )
      });
    },
    onConfirm() {
      const weekMap = {
        '周日': '星期天',
        '周一': '星期一',
        '周二': '星期二',
        '周三': '星期三',
        '周四': '星期四',
        '周五': '星期五',
        '周六': '星期六'
      };

      const { watch_info_id, device_imei } = this.data.formData;
      const { remind_date, remind_time, remind_type, days, remind_model } = this.data;

      if (!remind_time) {
        showToast('请选择提醒时间！');
        return;
      }

      this.triggerEvent('confirm', {
        watch_info_id,
        device_imei,
        remind_type,
        remind_model,
        ...(remind_model
          ? { remind_time: `${remind_date} ${remind_time}` }
          : {
              remind_cycle: days.filter((item) => item.isChecked).map((item) => weekMap[item.text]).join(','),
              remind_time
            }
        ),
        ...(this.data.formData.id ? { id: this.data.formData.id } : {})
      });
    }
  }
});
